package com.yy.jhl.ui.main.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;

import com.yy.common.base.BaseActivity;
import com.yy.common.commonutils.Base64;
import com.yy.common.commonutils.FileUtil;
import com.yy.common.commonutils.StringUtil;
import com.yy.common.commonwidget.OnNoDoubleClickListener;
import com.yy.jhl.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;

/**
 * <p> Do:拍照|相册操作并上传; <br/>
 * Tip:需Intent传递属性,如为空，将默认为正方形比例，小图上传，宽高360像素;
 * <br/> @author Lemon Thu 9 Mar 15:49 </p>
 * <li><code>Intent Params --> 可通过 {@link #getTakePhotoStartIntent(Context, String, int, int, int, int)} 方法</code>
 * <li> Key: IMAGE_TYPE Value: this.DO_BIG_IMAGE | this.DO_SMALL_IMAGE(default).
 * <li> Key: ASPECT_X Value: ...| 1(default).
 * <li> Key: ASPECT_Y Value: ...| 1(default).
 * <li> Key: OUTPUT_X Value: 640 | ... | 360(default).
 * <li> Key: OUTPUT_Y Value: 640 | ... | 360(default).
 */
public class TakePhotoUploadActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "TakePhotoUploadActivity";
    private static final int TAKE_BIG_PICTURE = 1;
    private static final int TAKE_SMALL_PICTURE = 2;
    private static final int CROP_BIG_PICTURE = 3;
    private static final int CROP_SMALL_PICTURE = 4;
    private static final int CHOOSE_BIG_PICTURE = 5;
    private static final int CHOOSE_SMALL_PICTURE = 6;
    //	private static final String IMAGE_FILE_LOCATION = "file:///sdcard/temp.jpg";
    private static String IMAGE_FILE_LOCATION;
    //	private static final String IMAGE_FILE_LOCATION = Environment.getExternalStorageDirectory().getPath()
//		+ "/" + "IMG_" + System.currentTimeMillis() + ".jpg";
    private Uri imageUri;//to store the big bitmap

    /**
     * 图片处理方式：大图使用URI传递，小图使用bitmap传递
     */
    private String imageType = DO_SMALL_IMAGE;
    /**
     * option param key
     */
    public static final String PARAM_IMAGE_TYPE = "IMAGE_TYPE";
    /**
     * option param key-图片宽度比例
     */
    public static final String PARAM_ASPECT_X = "ASPECT_X";
    /**
     * option param key-图片高度比例
     */
    public static final String PARAM_ASPECT_Y = "ASPECT_Y";
    /**
     * option param key-图片宽度
     */
    public static final String PARAM_OUTPUT_X = "OUTPUT_X";
    /**
     * option param key-图片高度
     */
    public static final String PARAM_OUTPUT_Y = "OUTPUT_Y";
    /**
     * option param IMAGE_TYPE's value
     */
    public static final String DO_BIG_IMAGE = "DO_BIG_IMAGE";
    /**
     * option param IMAGE_TYPE's value
     */
    public static final String DO_SMALL_IMAGE = "DO_SMALL_IMAGE";
    private int aspectX = 1;
    private int aspectY = 1;
    private int outputX = 360;
    private int outputY = 360;
    private boolean isShowTakePhoto = true;
    private LinearLayout album_parent,look_parent;
    String imagePath = "";
    @Override
    public int getLayoutId() {
        return R.layout.ac_take_photo;
    }

    @Override
    public void initView() {
        IMAGE_FILE_LOCATION = "file:///sdcard/IMG_" + + System.currentTimeMillis() + ".jpg";
        imageUri = Uri.parse(IMAGE_FILE_LOCATION);
        imagePath = getIntent().getStringExtra("path");
        isShowTakePhoto = getIntent().getBooleanExtra("isShowTakePhoto",true);
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            imageType = !StringUtil.isEmpty(bundle.getString(PARAM_IMAGE_TYPE)) ? bundle.getString(PARAM_IMAGE_TYPE) : DO_SMALL_IMAGE;
            aspectX = bundle.getInt(PARAM_ASPECT_X) != 0 ? bundle.getInt(PARAM_ASPECT_X) : 1;
            aspectY = bundle.getInt(PARAM_ASPECT_Y) != 0 ? bundle.getInt(PARAM_ASPECT_Y) : 1;
            outputX = bundle.getInt(PARAM_OUTPUT_X) != 0 ? bundle.getInt(PARAM_OUTPUT_X) : 360;
            outputY = bundle.getInt(PARAM_OUTPUT_Y) != 0 ? bundle.getInt(PARAM_OUTPUT_Y) : 360;
        }
        look_parent = (LinearLayout)findViewById(R.id.look_parent);
        album_parent = (LinearLayout)findViewById(R.id.album_parent);
        findViewById(R.id.textview_dialog_take_picture).setOnClickListener(this);
        findViewById(R.id.textview_dialog_album).setOnClickListener(this);
        findViewById(R.id.textview_dialog_cancel).setOnClickListener(this);
        findViewById(R.id.nullLinear).setOnClickListener(this);
        if (!isShowTakePhoto){
            album_parent.setVisibility(View.GONE);
        }
        if (!StringUtil.isEmpty(imagePath)){
            look_parent.setVisibility(View.VISIBLE);
            look_parent.setOnClickListener(new OnNoDoubleClickListener() {
                @Override
                protected void onNoDoubleClick(View v) {
                    ArrayList<String> paths = new ArrayList<String>();
                    paths.add(imagePath);
                    PhotosShowActivity.startAction(mContext,paths,0);
                    finish();
                }
            });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.textview_dialog_take_picture:
                if (imageUri == null)
                    Log.e(TAG, "image uri can't be null");
                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//action is capture
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//capture a big bitmap and store it in Uri
                if (imageType.equals(DO_BIG_IMAGE))
                    startActivityForResult(intent, TAKE_BIG_PICTURE);
                else
                    startActivityForResult(intent, TAKE_SMALL_PICTURE);
                break;
            case R.id.textview_dialog_album:
                 intent = new Intent(Intent.ACTION_PICK);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
                startActivityForResult(intent,1221);
//                intent = new Intent(Intent.ACTION_PICK, null);
//                intent.setType("image/*");
//                intent.putExtra("crop", "true");
//                intent.putExtra("aspectX", aspectX);
//                intent.putExtra("aspectY", aspectY);
//                intent.putExtra("outputX", outputX);
//                intent.putExtra("outputY", outputY);
//                intent.putExtra("scale", true);
//                if (imageType.equals(DO_BIG_IMAGE)) {
//                    intent.putExtra("return-data", false);
//                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//                    intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
//                    intent.putExtra("noFaceDetection", true); // no face detection
//                    startActivityForResult(intent, CHOOSE_BIG_PICTURE);
//                } else {
//                    intent.putExtra("return-data", true);
//                    intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
//                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//                    intent.putExtra("noFaceDetection", true); // no face detection
//                    startActivityForResult(intent, CHOOSE_SMALL_PICTURE);
//                }
                break;
            case R.id.textview_dialog_cancel: // 取消
            case R.id.nullLinear: // 空白处
                intent = new Intent();
                intent.putExtra("data", "");
                intent.putExtra("nativePath", "");
                setResult(RESULT_OK, intent);
                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) { //result is not correct
            Log.e(TAG, "requestCode = " + requestCode);
            Log.e(TAG, "resultCode = " + resultCode);
            Log.e(TAG, "data = " + data);
            return;
        } else {
            switch (requestCode) {
                case TAKE_BIG_PICTURE:
                    Log.e(TAG, "TAKE_BIG_PICTURE: data = " + data); //it seems to be null
                    cropImageUri(imageUri, CROP_BIG_PICTURE);
                    //TODO or decode as bitmap and display it
                    break;
                case TAKE_SMALL_PICTURE:
                    Log.e(TAG, "TAKE_SMALL_PICTURE: data = " + data);
                    cropImageUri(imageUri, CROP_SMALL_PICTURE);
                    //TODO or decode as bitmap and display it
                    break;
                case CHOOSE_BIG_PICTURE:
                    Log.e(TAG, "CHOOSE_BIG_PICTURE: data = " + data); //it seems to be null
                    if (imageUri != null) {
                        imageUri = data.getData();
//                        Bitmap bitmap = decodeUriAsBitmap(imageUri);
//                        final byte[] byteData = Bitmap2Bytes(bitmap);
//                        setResult(Base64.encodeBytes(byteData));
                        setResult("");
                    }
                    break;
                case CHOOSE_SMALL_PICTURE:
                    if (data != null) {
//                    if (imageUri != null) {
                        imageUri = data.getData();
//                        Bitmap bitmap = data.getParcelableExtra("data");
//                        final byte[] byteData = Bitmap2Bytes(bitmap);
//                        setResult(Base64.encodeBytes(byteData));
//                        setResult("");
                        cropImageUri(imageUri, CROP_SMALL_PICTURE);
                    }
                    break;
                case CROP_BIG_PICTURE: //from crop_big_picture
                    Log.e(TAG, "CROP_BIG_PICTURE: data = " + data); //it seems to be null
                    if (imageUri != null) {
                        Bitmap bitmap = decodeUriAsBitmap(imageUri);
                        final byte[] byteData = Bitmap2Bytes(bitmap);
                        setResult(Base64.encodeBytes(byteData));
                    }
                    break;
                case CROP_SMALL_PICTURE:
                    if (imageUri != null) {
                        Bitmap bitmap = decodeUriAsBitmap(imageUri);
                        final byte[] byteData = Bitmap2Bytes(bitmap);
                        setResult(Base64.encodeBytes(byteData));
                    } else {
                        Log.e(TAG, "CROP_SMALL_PICTURE: data = " + data);
                    }
                    break;
                case 1221:
                    String path = FileUtil.getImageAbsolutePath(this,data.getData());
                    File file = new File(path);
                    imageUri = Uri.fromFile(file);
                    cropImageUri(imageUri, CROP_BIG_PICTURE);
                    break;
                default:
                    break;
            }
        }
    }

    private void cropImageUri(Uri uri, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", aspectX);
        intent.putExtra("aspectY", aspectY);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, requestCode);
//        ClipImageActivity.startAction((Activity) mContext,uri);
    }

    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    public static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 50, baos);
        return baos.toByteArray();
    }

    public static final int UPLOAD_SUCCESS = 100;
    public static final int UPLOAD_IMG = 101;

    private void setResult(String imageData) {
        Intent intent = new Intent();
        intent.putExtra("DATA", imageData);
        intent.putExtra("PATH", imageUri);
        Log.e(TAG, "imageUri == " + imageUri);
        setResult(RESULT_OK, intent);
        finish();
    }

    /***
     * 获取跳转Intent数据
     * @param mContext 上下文
     * @param imageType 图片类型：大图或小图
     * @param aspectX 图片宽度比例
     * @param aspectY 图片高度比例
     * @param outputX 图片宽度
     * @param outputY 图片高度
     * @return
     */
    public static Intent getTakePhotoStartIntent(Context mContext, String imageType,
                                                 int aspectX, int aspectY,
                                                 int outputX, int outputY) {
        Intent intent = new Intent(mContext, TakePhotoUploadActivity.class);
        intent.putExtra(TakePhotoUploadActivity.PARAM_IMAGE_TYPE, imageType);
        intent.putExtra(TakePhotoUploadActivity.PARAM_ASPECT_X, aspectX);
        intent.putExtra(TakePhotoUploadActivity.PARAM_ASPECT_Y, aspectY);
        intent.putExtra(TakePhotoUploadActivity.PARAM_OUTPUT_X, outputX);
        intent.putExtra(TakePhotoUploadActivity.PARAM_OUTPUT_Y, outputY);
        return intent;
    }
    public static Intent getTakePhotoStartIntent(Context mContext, String imageType,
                                                 int aspectX, int aspectY,
                                                 int outputX, int outputY,boolean isShowTakePhoto,String path) {
        Intent intent = new Intent(mContext, TakePhotoUploadActivity.class);
        intent.putExtra(TakePhotoUploadActivity.PARAM_IMAGE_TYPE, imageType);
        intent.putExtra(TakePhotoUploadActivity.PARAM_ASPECT_X, aspectX);
        intent.putExtra(TakePhotoUploadActivity.PARAM_ASPECT_Y, aspectY);
        intent.putExtra(TakePhotoUploadActivity.PARAM_OUTPUT_X, outputX);
        intent.putExtra(TakePhotoUploadActivity.PARAM_OUTPUT_Y, outputY);
        intent.putExtra("isShowTakePhoto", isShowTakePhoto);
        intent.putExtra("path", path);
        return intent;
    }
}